package com.ego.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ego.admin.dao.SysCaptchaDao;
import com.ego.admin.po.SysCaptcha;
import com.ego.admin.service.SysCaptchaService;
import com.ego.common.exception.GlobalException;
import com.google.code.kaptcha.Producer;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.awt.image.BufferedImage;
import java.util.Date;

/**
 * @program: ego
 * @description:
 * @author: KamTang
 * @create: 2022-11-12 15:05
 **/
@Service("sysCaptchaService")
public class SysCaptchaServiceImpl extends ServiceImpl<SysCaptchaDao, SysCaptcha> implements SysCaptchaService {

    @Autowired
    private Producer producer;

    @Override
    public BufferedImage get(String uuid) {
        if (StringUtils.isBlank(uuid)) {
            throw new GlobalException("uuid不能为空");
        }
        // 生成文字验证码
        String code = producer.createText();

        SysCaptcha captchaEntity = new SysCaptcha();
        captchaEntity.setUuid(uuid);
        captchaEntity.setCode(code);
        // 3分钟后过期
        captchaEntity.setExpireTime(DateUtils.addMinutes(new Date(), 3));
        this.save(captchaEntity);

        return producer.createImage(code);
    }

    @Override
    public boolean validate(String uuid, String code) {
        SysCaptcha captchaEntity = this.getOne(new QueryWrapper<SysCaptcha>().eq("uuid", uuid));
        if (captchaEntity == null) {
            return false;
        }
        // 删除验证码
        this.removeById(uuid);

        return captchaEntity.getCode().equalsIgnoreCase(code) && captchaEntity.getExpireTime().getTime() >= System.currentTimeMillis();
    }
}
